package org.elucid.chess;

import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.apache.log4j.Logger;
import org.elucid.chess.BasicGame.PlayerConfig;
import org.elucid.chess.model.Game;
import org.elucid.chess.model.Move;
import org.elucid.chess.view.MainFrame;

public class Main {
	
	private static Logger log = Logger.getLogger(Main.class);
	/**
	 * 
	 * @param args
	 * @throws Exception
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws UnsupportedLookAndFeelException
	 */
	public static void main(String[] args) throws Exception, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
		UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());

		Game game = new BasicGame(PlayerConfig.CpuVsCpu);

		final MainFrame ui = new MainFrame(game);
		ui.setVisible(true);
		
		while (!game.isGameOver()) {
			Thread.yield();
			if( !ui.isPaused() )
			{
				Move move = null;
				if( game.getCurrentPlayer() instanceof CpuPlayer )
				{
					move = game.waitForPlayerMove();
				}
				else
				{
					while( move == null ){
						while( ui.getMove() == null )
						{
							Thread.yield();
						}
						move = ui.getMove();
						if( !game.listLegalMoves().contains(move) )
						{
							log.info("Illegal Move");
							
							move = null;
							ui.resetMoveUi();
						}
						ui.setMove(null);
					}
				}
				
				if( move == null )
				{
					game.setGameOver(true);
				}
				else
				{
					game.doMove(move);
					ui.update(move);
					ui.setFromSquare(null);
				}
				
			}
		}
	}
}
